package com.gzmu.storage.controller;


import com.gzmu.storage.config.MyRealm;
import com.gzmu.storage.entity.Adminlog;
import com.gzmu.storage.entity.User;
import com.gzmu.storage.service.AdminlogService;
import com.gzmu.storage.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaobo Yan
 * @since 2020-04-16
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AdminlogService adminlogService;

    @ResponseBody
    @RequestMapping("getUser")
    public Object getUser(String id){
        return userService.selectById( id );
    }

    @RequestMapping("/login")
    public Map<String, Object> login(User user, BindingResult bindingResult) {
        Map<String, Object> map = new HashMap<>();
        // 1、JSR303
        if (bindingResult.hasErrors()) {
            map.put("code", 0);
            map.put("errorInfo", bindingResult.getFieldError().getDefaultMessage());
            return map;
        }
        // 2、Shiro
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            subject.login(token);
            map.put("code", 200);
            map.put("errorInfo", "登录成功!");
            adminlogService.insertAdminlog("登陆系统");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 1);
            map.put("errorInfo", "用户名或者密码错误!");
            return map;
        }
    }

    /**
     * 管理员退出
     *
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/logout")
    public String logout() {
        adminlogService.insertAdminlog("退出系统");
        SecurityUtils.getSubject().logout();
        return "/index";
    }
}

